package com.ukao.pad.ui.enterFactory;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.LogisticsAdapter;
import com.ukao.pad.adapter.StartFactoryAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.FactoryBatchInBean;
import com.ukao.pad.bean.ProductBatchInBean;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.DialogTool;
import com.ukao.pad.dialog.StartCountDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.presenter.StartFactoryPesenter;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.StartFactoryView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.CustomPopWindow;
import com.ukao.pad.widget.DividerDecoration;
import com.ukao.pad.widget.MyLRecyclerView;
import com.ukao.pad.widget.PercentLinearLayout;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.hoang8f.android.segmented.SegmentedGroup;
import me.yokeyword.fragmentation.SupportActivity;

import static com.ukao.pad.R.id.check_btn;
import static com.ukao.pad.R.id.radio_button1;
import static com.ukao.pad.R.id.start_count_btn;
import static com.ukao.pad.R.id.sure_factory;


public class StartFactoryFragment extends MvpFragment<StartFactoryPesenter> implements StartFactoryView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.search_edit_text)
    ClearEditText searchEditText;
    @BindView(R.id.search_button)
    StateImageView searchButton;
    @BindView(R.id.logistics_recycler_view)
    RecyclerView logisticsRecyclerView;

    Unbinder unbinder;
    @BindView(R.id.no_data)
    TextView noData;

    @BindView(R.id.deficiency_btn)
    StateButton deficiencyBtn;
    @BindView(R.id.rfid_btn)
    StateImageView rfidBtn;


    @BindView(R.id.productsum)
    TextView productsum;
    @BindView(R.id.productCnt)
    TextView productCnt;
    @BindView(R.id.already_productsum)
    TextView alreadyProductsum;
    @BindView(R.id.already_productCnt)
    TextView alreadyProductCnt;
    @BindView(R.id.left_include)
    LinearLayout leftInclude;
    @BindView(R.id.code_name)
    TextView codeName;
    @BindView(radio_button1)
    RadioButton radioButton1;
    @BindView(R.id.radio_button3)
    RadioButton radioButton3;
    @BindView(R.id.radio_button2)
    RadioButton radioButton2;
    @BindView(R.id.segmented_group)
    SegmentedGroup segmentedGroup;
    @BindView(R.id.sure_factory)
    StateButton sureFactory;
    @BindView(R.id.print_factory_receipt_btn)
    StateButton printFactoryReceiptBtn;
    @BindView(R.id.check_btn)
    StateButton checkBtn;
    @BindView(R.id.start_count_btn)
    StateButton startCountBtn;
    @BindView(R.id.no_right_data)
    TextView noRightData;
    @BindView(R.id.right_include)
    PercentLinearLayout rightInclude;
    @BindView(R.id.count_RecyclerView)
    MyLRecyclerView countRecyclerView;



    private String mParam1;
    private String mParam2;
    private StartFactoryAdapter mStartFactoryAdapter;
    private ArrayList<ProductBatchInBean> mCountData;
    private LogisticsAdapter mLogisticsAdapter;

    private CustomPopWindow mReportLossWindow;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private ArrayList<FactoryBatchInBean> mLogisticsData;
    private String batchInId;
    private int alreadyCount;/*已经点的数目*/
    private int mProductSum;/*衣服总数*/
    private int loseFactoryCount;/*上报缺失数*/
    private boolean isFinish;/*是否完成*/
    public String clotgingId;/*id*/
    public String intId;
    private int notCheck;

    private StartCountDialogFragment mStartCountDialog;
    private CustomPopWindow mAllCheckWindow;
    private FactoryBatchInBean mBatchInBean;


    public static StartFactoryFragment newInstance(String param1, String param2) {
        StartFactoryFragment fragment = new StartFactoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected StartFactoryPesenter createPresenter() {
        return new StartFactoryPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_start_factory, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initAdapter();
        initListener();
        return view;
    }



    @Override
    protected void initView() {
        switch (SaveParamets.getOrderEnter()){
            case  1:
                radioButton1.setChecked(true);
                break;
            case  2:
                radioButton2.setChecked(true);
                break;
            case  3:
                radioButton3.setChecked(true);
                break;

        }

        searchEditText.requestFocus();
        mCountData = new ArrayList<>();
        mLogisticsData = new ArrayList<>();

    }

    @Override
    protected void initAdapter() {
        super.initAdapter();
        initLinearRecyclerView(countRecyclerView);
        countRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        countRecyclerView.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        mStartFactoryAdapter = new StartFactoryAdapter(_mActivity, mCountData);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mStartFactoryAdapter);
        countRecyclerView.setAdapter(mLRecyclerViewAdapter);
        initLinearRecyclerView(logisticsRecyclerView);
        mLogisticsAdapter = new LogisticsAdapter(_mActivity, mLogisticsData);
        logisticsRecyclerView.setAdapter(mLogisticsAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mStartFactoryAdapter.setOnItemClickListener(mOnItemClickListener);
        countRecyclerView.setOnRefreshListener(mOnRefreshListener);
        searchEditText.setOnEditorActionListener(mOnEditorAction);


    }


    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                hideSoftInput();
                searchBatch();
            }

            return false;
        }
    };


    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            if (mBatchInBean.getEnterFactoryType()==3){
                refreshFinish();
            }else {
                mvpPresenter.productBatchInlist( batchInId,mBatchInBean);
            }


        }
    };

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {


        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            if (mStartFactoryAdapter.getItem(i)!=null){
                ProductBatchInBean item =mStartFactoryAdapter.getItem(i);
                if (mBatchInBean.getEnterFactoryType()==1){
                    intId = item.getInId();
                }
                if (item.getStatus() == 0) {
                    item.setCheck(!item.isCheck());
                    mLRecyclerViewAdapter.notifyDataSetChanged();
                }
            }




        }
    };

    private String getLossClothingId() {
        clotgingId = "";
        StringBuffer mStringBuffer = new StringBuffer();
        for (int j = 0; j < mCountData.size(); j++) {
            ProductBatchInBean mCountitem = mCountData.get(j);
            if (mCountitem.isCheck()) {

                mStringBuffer.append(mCountitem.getId() + ",");
            }

        }
        if (mStringBuffer.length() != 0)
            clotgingId = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();

        return clotgingId;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();
        unbinder.unbind();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {
        switch (event.getMessage()) {
            case cardNum:/*成功*/
                if (!CheckUtils.isNull(mStartCountDialog) && mStartCountDialog.getDialog() != null && mStartCountDialog.getDialog().isShowing())return;
                String rfidSecretCard = (String) event.getData();
                searchEditText.setText(rfidSecretCard);
                searchBatch();
                break;
        }
    }
    @OnCheckedChanged({radio_button1, R.id.radio_button2,R.id.radio_button3})
    public void OnCheckedChanged(CompoundButton view, boolean checked) {
        if (checked) {
            switch (view.getId()) {
                case radio_button1:
                    UsbrfidReaderHelper.getInstance().cancelReadCardNum();
                    searchEditText.setHint("入厂袋号");
//                    if (SaveParamets.isOrderEnter()){   mvpPresenter.updateInType(1,radioButton2 );    }
                    rfidBtn.setVisibility(View.GONE);
                    break;
                case R.id.radio_button2:
                    UsbrfidReaderHelper.getInstance().cancelReadCardNum();
                    searchEditText.setHint("订单号/运单号");
//                    if (!SaveParamets.isOrderEnter()){   mvpPresenter.updateInType(2,radioButton1 );  }
                    rfidBtn.setVisibility(View.GONE);
                    break;
                case R.id.radio_button3:
                    UsbrfidReaderHelper.getInstance().readCardNum();
                    searchEditText.setHint("衣物条码/标号");
//                    if (!SaveParamets.isOrderEnter()){   mvpPresenter.updateInType(2,radioButton1 );  }
                    rfidBtn.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (radioButton3.isChecked())
        UsbrfidReaderHelper.getInstance().readCardNum();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();
        switch (segmentedGroup.getCheckedRadioButtonId()){
            case R.id.radio_button1 :
                SaveParamets.setOrderEnter(1);
                break;
            case R.id.radio_button2 :
                SaveParamets.setOrderEnter(2);
                break;
            case R.id.radio_button3 :
                SaveParamets.setOrderEnter(3);
                break;
        }

    }
    @OnClick({R.id.search_button, start_count_btn, R.id.deficiency_btn, sure_factory, check_btn, R.id.rfid_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.rfid_btn:
                UsbrfidReaderHelper.getInstance().readCardNum();
                break;
            case check_btn: /*已全部核对*/
                if (CheckUtils.isEmpty(batchInId)) return;
                mAllCheckWindow = DialogTool.getSingleton().showPopReportLoss(_mActivity, sureFactory, "是否全部核对衣物数量？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAllCheckWindow.dissmiss();
                        mvpPresenter.allCompleteCheck( batchInId,mBatchInBean.getEnterFactoryType());
                    }
                });


                break;

            case R.id.search_button:/*搜索袋号*/

                searchBatch();

                break;

            case start_count_btn:/*开始点数*/

                if (CheckUtils.isEmpty(mStartFactoryAdapter.getDatas())) return;
                ArrayList<ProductBatchInBean> mdata = (ArrayList<ProductBatchInBean>) mStartFactoryAdapter.getDatas();
                mStartCountDialog = new StartCountDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putParcelableArrayList(ARG_PARAM1, mdata);
                mBundle.putBoolean(ARG_PARAM2, false);
                mStartCountDialog.setArguments(mBundle);
                mStartCountDialog.setOnCounntSucceedListener(mOnCounntSucceed);
                mStartCountDialog.show(getChildFragmentManager(),"mStartCountDialog");


                break;
            case R.id.deficiency_btn:/*上报缺失*/
                if (CheckUtils.isEmpty(getLossClothingId())) return;
                mReportLossWindow = DialogTool.getSingleton().showPopReportLoss(_mActivity, startCountBtn, null, mOnClickListener);
                break;
            case sure_factory:

                if (!CheckUtils.isEmpty(batchInId)&&mBatchInBean!=null) {
                      mvpPresenter.sureConfirmFactory(batchInId,mBatchInBean.getEnterFactoryType());
                }
                break;


        }
    }

    private void searchBatch() {
        String strsearchEditText = getText(searchEditText);
        if (CheckUtils.isEmpty(strsearchEditText)) return;
         hideSoftInput();
        mvpPresenter.receiveFactory(_mActivity, strsearchEditText,segmentedGroup);

    }


    /**
     * 点数
     */
    private StartCountDialogFragment.OnCounntSucceedListener mOnCounntSucceed = new StartCountDialogFragment.OnCounntSucceedListener() {
        @Override
        public void onCounntSucceed(int pos) {
            ProductBatchInBean item = mStartFactoryAdapter.getItem(pos);
            item.setStatusText("已核对");
            if (item.isOrder()){
                item.setIsFactoryStatus(1);
            }else{
                item.setStatus(1);
            }
            alreadyCount = alreadyCount + 1;
            mLRecyclerViewAdapter.notifyDataSetChanged();
            showTotalCountStyle();


        }
    };

    /**
     * 显示所有点数 以及样式
     */
    private void showTotalCountStyle() {
        alreadyProductsum.setText("共点数 " + alreadyCount + " 件");
        if (notCheck != 0) { /*未核对数不为0  就显示异常按钮*/
            checkBtn.setVisibility(View.VISIBLE);
           deficiencyBtn.setVisibility( mBatchInBean.getEnterFactoryType()==1?  View.VISIBLE:View.GONE);
            startCountBtn.setVisibility(View.VISIBLE);
            sureFactory.setVisibility(View.GONE);
        } else if (notCheck == 0) {
            checkBtn.setVisibility(View.GONE);
            deficiencyBtn.setVisibility(View.GONE);
            startCountBtn.setVisibility(View.GONE);
            sureFactory.setVisibility(isFinish ? View.GONE : View.VISIBLE);
        }
        if (mProductSum > alreadyCount) {   /* 点完的数据   点的数量小于总数 但是上报缺失数量等于总数*/
            alreadyProductsum.setTextColor(resources.getColor(R.color.normal_red));
            alreadyProductCnt.setTextColor(resources.getColor(R.color.normal_red));
            /*异常总数==衣服总数*/
            if (!isFinish && alreadyCount > 0) {
                sureFactory.setVisibility(alreadyCount + loseFactoryCount == mProductSum ? View.VISIBLE : View.GONE);
            }
            if (alreadyProductsum.getVisibility() == View.GONE)
                alreadyProductsum.setVisibility(View.VISIBLE);
            alreadyProductCnt.setVisibility(View.VISIBLE);
        } else if (mProductSum == alreadyCount) {  /*全部核对数量*/
            if (!CheckUtils.isNull(mStartCountDialog) && mStartCountDialog.getDialog() != null && mStartCountDialog.getDialog().isShowing()) {
                countRecyclerView.forceToRefresh();
                mStartCountDialog.dismiss();
            }
            alreadyProductsum.setTextColor(resources.getColor(R.color.green));
            alreadyProductCnt.setTextColor(resources.getColor(R.color.green));
            sureFactory.setVisibility(isFinish ? View.GONE : View.VISIBLE);
            deficiencyBtn.setVisibility(View.GONE);
            checkBtn.setVisibility(View.GONE);
            startCountBtn.setVisibility(View.GONE);

        }


    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.submit:
                    if (!clotgingId.isEmpty()) {
                        mvpPresenter.loseFactory(_mActivity, clotgingId, intId);
                        mReportLossWindow.dissmiss();
                    }

                    break;
            }

        }
    };


    @Override
    public void loadbatchSuccess(FactoryBatchInBean mitem) {
        this.mBatchInBean=mitem;
        alreadyCount = 0;
        if (!CheckUtils.isNull(mitem.getStoreName())) {
            mLogisticsData.clear();
            FactoryBatchInBean mBatchInBean1 = new FactoryBatchInBean(mitem.getStoreName(), mitem.getStoreWorkTime(), true);
            mLogisticsData.add(mBatchInBean1);
            FactoryBatchInBean mBatchInBean2 = null;
            if (!CheckUtils.isEmpty(mitem.getLogisticsWorkName())) {
                mBatchInBean2 = new FactoryBatchInBean(mitem.getLogisticsWorkName(), mitem.getLogisticsWorkTime(), true);
            } else {
                mBatchInBean2 = new FactoryBatchInBean("", 0, false);

            }
            FactoryBatchInBean mBatchInBean3 = null;
            if (!CheckUtils.isNull(mitem.getFactoryName())) {
                boolean isgreed = false;
                if (mBatchInBean2.isgreed()||mBatchInBean.getStatusFinish()||mBatchInBean.isFinishStockIn()) {
                    isgreed = true;
                }
                mBatchInBean3 = new FactoryBatchInBean(mitem.getFactoryName(), mitem.getFactoryWorkTime(), isgreed);

            } else {
                mBatchInBean3 = new FactoryBatchInBean("未知", 0, false);

            }
            mLogisticsData.add(mBatchInBean2);
            mLogisticsData.add(mBatchInBean3);
            mLogisticsAdapter.setDatas(mLogisticsData);

        }
        switch (mitem.getEnterFactoryType()){

            case  1  :
                codeName.setText("入厂袋号：" + mitem.getCode());
                batchInId = mitem.getId();
                isFinish = mitem.getStatusFinish();
                break;
            case  2  :
                isFinish =mBatchInBean.isFinishStockIn();
                batchInId = mitem.getOrderId();
                codeName.setText("订单号："+mitem.getOrderNo());
                break;
            case  3  :
                codeName.setText("条码："+mitem.getScanCode());
                isFinish =true;
                loadbatchListSuccess(mitem.getProList());
                break;
        }
        leftInclude.setVisibility(View.VISIBLE);
        productCnt.setText(mitem.getProductCnt() + mitem.getAnnexCnt());
        mProductSum = mitem.getallProductSum();
        productsum.setText(mitem.getProductSum());
        alreadyProductCnt.setText(mitem.getProductCnt() + mitem.getAnnexCnt());
        if (mitem.getEnterFactoryType()!=3){
            countRecyclerView.forceToRefresh();
        }
        cleanCode();

    }

    /**
     * 获取批次列表
     */
    @Override
    public void loadbatchListSuccess(List<ProductBatchInBean> mFactoryBatchInBean) {
        alreadyCount = 0;
        loseFactoryCount = 0;
        notCheck = 0;
        if (CheckUtils.isEmpty(mFactoryBatchInBean)) {
            noRightData.setVisibility(View.VISIBLE);
            startCountBtn.setVisibility(View.GONE);
            deficiencyBtn.setVisibility(View.GONE);
            sureFactory.setVisibility(View.GONE);
            rightInclude.setVisibility(View.GONE);
            countRecyclerView.setVisibility(View.GONE);
        } else {
            rightInclude.setVisibility(View.VISIBLE);
            noRightData.setVisibility(View.GONE);
            countRecyclerView.setVisibility(View.VISIBLE);

            for (int i = 0; i < mFactoryBatchInBean.size(); i++) {
                ProductBatchInBean mitem = mFactoryBatchInBean.get(i);
                mitem.setOrder( mBatchInBean.getEnterFactoryType()!=1);
                int mstatus =  mBatchInBean.getEnterFactoryType()!=1?mitem.getIsFactoryStatus():mitem.getStatus();
                switch (mstatus) {
                    case 2:
                        loseFactoryCount = loseFactoryCount + 1;
                        break;
                    case 1: /*已点数*/
                        alreadyCount = alreadyCount + 1;
                        break;
                    case 0: /*未点数*/
                        notCheck = notCheck + 1;
                        break;
                }
            }


        }
        mStartFactoryAdapter.getDatas().clear();
        mStartFactoryAdapter.setDatas(mFactoryBatchInBean);
        mLRecyclerViewAdapter.notifyDataSetChanged();
        showTotalCountStyle();


    }



    @Override
    public void refreshFinish() {
        countRecyclerView.refreshComplete(10);
    }


    @Override
    public void loadFail(String errs) {
        T.show(errs);
    }

    private void clearInitState() {
        checkBtn.setVisibility(View.GONE);
        KeyBoardUtil.hideInputmethod(searchEditText);
        searchEditText.setText("");
        mLogisticsAdapter.getDatas().clear();
        mLogisticsAdapter.notifyDataSetChanged();
        mStartFactoryAdapter.getDatas().clear();
        mStartFactoryAdapter.notifyDataSetChanged();
        sureFactory.setVisibility(View.GONE);
        startCountBtn.setVisibility(View.GONE);
       deficiencyBtn.setVisibility(View.GONE);
        leftInclude.setVisibility(View.GONE);
        rightInclude.setVisibility(View.GONE);
        alreadyCount = 0;
        loseFactoryCount = 0;

    }

    /**
     * 入厂成功恢复到开始界面
     */
    @Override
    public void sureFactorySuccess() {

        DialogTool.getSingleton().showPopEnterFactory(false, (SupportActivity) _mActivity, startCountBtn);
        clearInitState();
    }

    /**
     * 上报缺失
     */
    @Override
    public void loseFactorySuccess(String message) {
        T.show(message);
        countRecyclerView.forceToRefresh();
    }

    private void cleanCode() {
        searchEditText.setText("");
        searchEditText.requestFocus();
        KeyBoardUtil.hideInputmethod(searchEditText);



    }

    @Override
    public void loadbatchFile(String msg) {
        cleanCode();
        T.show(msg);
    }

    /**
     * 已全部核对
     *
     * @param msg
     */
    @Override
    public void checkAllFactory(String msg) {

        countRecyclerView.forceToRefresh();
        checkBtn.setVisibility(View.GONE);
        startCountBtn.setVisibility(View.GONE);
        deficiencyBtn.setVisibility(View.GONE);
}

    /**
     * 修改操作类型失败
     */
    @Override
    public void updateInTypeFail(RadioButton mRadioButton) {
        mRadioButton.setChecked(true);
    }


}